package com.spr.gw.service.impl;

import com.spr.gw.common.ResponseCode;
import com.spr.gw.common.ResultBean;
import com.spr.gw.entity.Category;
import com.spr.gw.mapper.CategoryMapper;
import com.spr.gw.service.SinglePageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class SinglePageServiceImpl implements SinglePageService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ResultBean<List<Category>> findAll() {
        List<Category> categories = categoryMapper.selectAll();
        return ResultBean.createBySuccess(categories);
    }

    @Override
    public ResultBean<Category> findOne(Integer categoryId) {
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        return ResultBean.createBySuccess(category);
    }

    @Override
    public ResultBean<Category> addOrUpdate(Category category) {
        //通过是否有id来判断更新还是添加
        if (StringUtils.isEmpty(category.getCategoryId())) {
            category.setCreateTime(new Date());
            category.setUpdateTime(new Date());
            category.setPid(0);
            int i = categoryMapper.insert(category);
            if (i != 0) {
                return ResultBean.createBySuccessMessage("添加成功");
            } else {
                return ResultBean.createByCodeMessage(ResponseCode.ADD_ERROR.getCode(),ResponseCode.ADD_ERROR.getDesc());
            }
        } else {
            category.setUpdateTime(new Date());
            int i = categoryMapper.updateByPrimaryKeySelective(category);
            if (i != 0) {
                return ResultBean.createBySuccessMessage("更新成功");
            } else {
                return ResultBean.createByCodeMessage(ResponseCode.UPDATE_ERROR.getCode(),ResponseCode.UPDATE_ERROR.getDesc());
            }
        }


    }

    @Override
    public ResultBean<Category> deleteOne(Integer id) {
        int i = categoryMapper.deleteByPrimaryKey(id);
        if (i != 0) {
            return ResultBean.createBySuccessMessage("删除成功");
        } else {
            return ResultBean.createByCodeMessage(ResponseCode.ERROR.getCode());
        }
    }
}
